<template>
  <Spin :spinning="spinning">
    <Card class="spu-setting" :bordered="false">
      <Button @click="back">返回</Button>

      <!--      基础信息-->
      <SettingBasicInfo ref="basicInfoRef" :details="spuConfig" />
      <!--      规格配置-->
      <SettingSpuSpec ref="spuSpecRef" :spu-config="spuConfig" @save="handleSave" />
      <!--      底部操作栏-->
      <div class="action-container flex-row-center-end">
        <Button :type="'primary'" style="margin-right: 10px" @click="handleAdd">添加规格</Button>
        <Button :type="'primary'" @click="handleSave">保存</Button>
      </div>
      <!--      添加规格选择模态框-->
      <AddSpecModal @register="registerModal" @add="handleAddSpecOk" />
    </Card>
  </Spin>
</template>

<script setup lang="ts">
  import { cloneDeep } from 'lodash-es';
  import { useRoute } from 'vue-router';
  import mcApi from 'mc-c2b2m-operator-api';
  import { back } from '@/hooks/web/useCommon';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Card, Spin, Button } from 'ant-design-vue';
  import SettingSpuSpec from './components/SpuSpec.vue';
  import SettingBasicInfo from './components/BasicInfo.vue';
  import { handleSpuDetails } from '@/hooks/web/useSpuAction';
  import { onBeforeUnmount, provide, ref, toRefs } from 'vue';
  import { defaultSpuSpec } from '@/views/spu/spu/setting/data';
  import { SpuSpecificationTypeEnum, UiComponentEnum } from '@/enums/spuEnum';
  import AddSpecModal from '@/views/spu/spu/setting/components/AddSpecModal.vue';
  import {
    SpuSpecModel,
    BizMetaAttrTreeModel,
    SpuConfigurationModel,
  } from 'mc-c2b2m-operator-api/types/spu';

  const { SpuModule } = mcApi;
  const { SpuApi, BizMetaArrApi } = SpuModule;

  const { createMessage } = useMessage();

  const basicInfoRef = ref();
  const spuSpecRef = ref();
  const spinning = ref<boolean>(false);
  const route = useRoute();
  const query = route.query || {};
  const id = query?.id as string;
  const spuConfig = ref<SpuConfigurationModel>();
  id &&
    SpuApi.getSpuConfiguration(id).then((res: SpuConfigurationModel) => {
      res['sortNo'] = query.sortNo;
      handleSpuDetails(res);
      handleSpecRelation(res?.spuSpecList || []);
      spuConfig.value = res || {};
    });
  // 处理规格节点关系数据
  const specRelation = ref<any>({});
  function handleSpecRelation(spuSpecList: SpuSpecModel[], parent?: SpuSpecModel) {
    spuSpecList?.forEach?.((item) => {
      const { id, childSpuSpecList } = item;
      specRelation.value[id] = parent || null;
      handleSpecRelation(childSpuSpecList, item);
    });
  }

  const treeData = ref<any>([]);
  const treeFlatData = ref<any>([]);
  // 获取业务元信息树
  BizMetaArrApi.getBizMetaAttrTree().then((res: BizMetaAttrTreeModel[]) => {
    treeData.value = res || [];
    handleTreeFlatData(treeData.value);
  });
  // 处理扁平化树数据源
  function handleTreeFlatData(data: any) {
    data?.forEach?.((item: any) => {
      const { id, cnName, childBizMetaAttrList: children } = item;
      treeFlatData.value.push({ id, cnName });
      handleTreeFlatData(children);
    });
  }
  provide('treeData', treeData);
  provide('treeFlatData', treeFlatData);

  const [registerModal, { openModal, closeModal }] = useModal();
  // 添加规格
  function handleAdd() {
    openModal(true);
  }
  // 添加规格成功
  function handleAddSpecOk(type: SpuSpecificationTypeEnum) {
    const ifGroup = type === SpuSpecificationTypeEnum.GROUP;
    spuConfig.value?.spuSpecList?.push?.({
      ...cloneDeep(defaultSpuSpec),
      type,
      uiComponent: ifGroup ? UiComponentEnum.GROUP : '',
    });
    closeModal();
    // 定位到页面最底部
    window.scrollTo(0, document.documentElement.clientHeight);
  }
  // 表单提交模型
  const postModel: any = ref({});
  // 规格项表单校验列表
  const formRefList: any = ref([]);
  // 保存操作
  async function handleSave() {
    try {
      spinning.value = true;
      // 数据提交模型赋值
      postModel.value = cloneDeep(spuConfig.value);
      // 基本信息校验与赋值
      const basicInfo = await basicInfoRef.value?.validate?.();
      postModel.value = { ...postModel.value, ...basicInfo };
      // 规格项配置的校验
      let valid = true;
      formRefList.value = [];
      await handleSpecValidate();
      try {
        for (let i = 0; i < formRefList.value.length; i++) {
          const formRef = formRefList.value[i];
          await formRef?.validate?.();
        }
      } catch {
        valid = false;
      }
      if (!valid) return;
      // 处理图片数据
      const { imgList } = postModel.value;
      postModel.value.picList =
        imgList?.map((img: string, index: number) => {
          return {
            type: 1,
            url: img,
            sortNo: index,
          };
        }) || [];
      delete postModel.value.imgList;
      handleSpuSpecListBySave(postModel.value.spuSpecList || []);
      console.log('postModel', postModel.value);
      await SpuApi.updateSpuConfiguration(postModel.value);
      createMessage.success('保存成功！');
      await SpuApi.getSpuConfiguration(postModel.value.id);
    } catch (e) {
      console.log('保存盒型参数配置异常：', e);
      createMessage.error('保存异常：', e);
    } finally {
      spinning.value = false;
    }
  }
  provide('handleSave', handleSave);
  // 数据提交时，递归处理规则列表
  function handleSpuSpecListBySave(spuSpecList: any[]) {
    spuSpecList?.forEach?.((item: any, index: number) => {
      item.sort = index + 1;
      handleSpuSpecListBySave(item?.childSpuSpecList);
    });
  }
  // 规格项配置的校验
  async function handleSpecValidate(specRef = spuSpecRef) {
    // 取出规格组以及规格项表单
    const { specGroupRef, specBasicInfoRef } = toRefs(specRef.value);
    specBasicInfoRef?.value?.forEach?.((ref: any) => {
      const formRef = ref?.formRef;
      formRef && formRefList.value.push(formRef);
    });
    await handleSpecGroupRef(specGroupRef);
  }
  // 规格项配置，规格组的校验相关
  async function handleSpecGroupRef(specGroupRef: any) {
    for (let i = 0; i < specGroupRef.value?.length; i++) {
      const { formRef, spuSpecRef } = toRefs(specGroupRef.value[i]);
      formRef?.value && formRefList.value.push(formRef.value);
      spuSpecRef?.value && (await handleSpecValidate(spuSpecRef));
    }
  }
  // 获取节点所属路径
  provide('handlePathName', (id: string) => handlePathName(id));
  function handlePathName(id: string, pathNameList: any = []) {
    const parent = specRelation.value[id];
    if (parent) {
      const { id: parentId, displayName } = parent;
      pathNameList.push(displayName);
      handlePathName(parentId, pathNameList);
    }
    return pathNameList;
  }

  // 拖拽相关配置
  const sortableList = ref<any>([]);
  // 新拖拽初始化事件
  provide('handleNewSortable', (sortable: any) => {
    !sortableList.value.includes(sortable) && sortableList.value.push(sortable);
  });
  const timer = ref<any>();
  // 统一处理拖拽对象的禁用事件
  provide('handleSortableDisabled', (disabled: boolean) => {
    timer.value = setTimeout(() => {
      sortableList.value.forEach((item: any) => (item.options.disabled = disabled));
    }, 100);
  });
  onBeforeUnmount(() => clearTimeout(timer.value));
</script>

<style scoped lang="less">
  .spu-setting {
    height: 100%;
    position: relative;
    padding-bottom: 70px;

    .action-container {
      left: 0;
      bottom: 0;
      width: 100%;
      padding: 10px;
      position: fixed;
      background: #fff;
      border: 1px solid gray;
    }
  }
</style>
